<template>
  <view class="review-page">
    <Navbar title="告警审核" />
    <view class="review-content">
      <template v-if="loading">
        <view class="loading-container">
          <text class="loading-text">加载中...</text>
        </view>
      </template>
      <template v-else-if="currentAlarm">
        <!-- 退回记录（有就显示，没有就不显示） -->
        <view
          v-if="rejectRecords.length > 0"
        >
          <view
            v-for="(record, idx) in rejectRecords"
            :key="idx"
          >
            <view class="alarm-info-card">
              <view class="info-row">
                <view class="info-label">退回时间</view>
                <view class="info-value">{{ record.reviewTime }}</view>
              </view>
              <view class="info-row">
                <view class="info-label">处理时间</view>
                <view class="info-value">{{ record.processTime }}</view>
              </view>
              <view class="info-row">
                <view class="info-label">退回人</view>
                <view class="info-value">{{ record.reviewerInfo?.realName }}</view>
              </view>
              <view class="info-row">
                <view class="info-label">处理人</view>
                <view class="info-value">{{ record.processorInfo?.realName }}</view>
              </view>
            </view>
                         <!-- 状态卡片（只在第一个退回记录且有待审核状态时显示） -->
                           <view v-if="idx === 0 && hasPendingReview" class="content-card">
                <view class="status-title">处理状态</view>
                <image
                  class="status-content"
                  :src="getStatusImageSrc"
                  mode="widthFix"
                ></image>
                <view class="status-content-text">
                  <view>告警</view>
                  <view>接警</view>
                  <view>处理</view>
                  <view>审核</view>
                </view>
               <image
                 class="left-bottom"
                 src="/static/img/left-bottom.png"
                 mode="widthFix"
               ></image>
               <image
                 class="right-bottom"
                 src="/static/img/right-bottom.png"
                 mode="widthFix"
               ></image>
               <image
                 class="left-top"
                 src="/static/img/left-top.png"
                 mode="widthFix"
               ></image>
               <image
                 class="right-top"
                 src="/static/img/right-top.png"
                 mode="widthFix"
               ></image>
             </view>

            <!-- 退回记录合并卡片 -->
            <view class="content-card">
              <view class="card-title">退回原因</view>
              <view class="card-content">{{ record.returnReason }}</view>
              <view class="card-title">处理建议</view>
              <view class="card-content">{{ record.returnSuggestion }}</view>
              <view class="card-title">再次处理方法</view>
              <view class="card-content">{{ record.solutionMethod }}</view>
              <view v-if="record.alertProcessImages && record.alertProcessImages.length > 0" class="card-title">图片查看</view>
              <scroll-view v-if="record.alertProcessImages && record.alertProcessImages.length > 0" class="image-list" scroll-x>
                <image
                  v-for="(img, imgIndex) in record.alertProcessImages"
                  :key="imgIndex"
                  :src="img.fileUrl"
                  class="image-item"
                  mode="aspectFill"
                  @click="previewImage(img.fileUrl, record.alertProcessImages.map(item => item.fileUrl))"
                  @error="handleImageError"
                />
              </scroll-view>
              <image
                class="left-bottom"
                src="/static/img/left-bottom.png"
                mode="widthFix"
              ></image>
              <image
                class="right-bottom"
                src="/static/img/right-bottom.png"
                mode="widthFix"
              ></image>
              <image
                class="left-top"
                src="/static/img/left-top.png"
                mode="widthFix"
              ></image>
              <image
                class="right-top"
                src="/static/img/right-top.png"
                mode="widthFix"
              ></image>
            </view>

            <!-- 在最新退回记录下方显示提示文字 -->
            <view v-if="idx === 0 && hasPendingReview" class="history-tip">
              以下为历史处理记录
            </view>

            <!-- 分割线 -->
            <view
              v-if="idx < rejectRecords.length - 1"
              class="divider"
            ></view>
          </view>
        </view>
        <!-- 普通流程卡片（根据逻辑判断是否显示） -->
        <view v-if="showNormalFlow" class="alarm-info-card">
          <view class="info-row">
            <view class="info-label">告警时间</view>
            <view class="info-value">{{ alertTime }}</view>
          </view>
          <view class="info-row">
            <view class="info-label">接警时间</view>
            <view class="info-value">{{ receiveTime }}</view>
          </view>
          <view class="info-row">
            <view class="info-label">处理时间</view>
            <view class="info-value">{{ currentAlarm?.processTime }}</view>
          </view>
          <view class="info-row">
            <view class="info-label">处理人</view>
            <view class="info-value">{{ currentAlarm?.processorInfo?.realName }}</view>
          </view>
        </view>

                 <!-- 状态卡片（无退回记录时显示） -->
         <view
           v-if="showNormalFlow && rejectRecords.length === 0"
           class="content-card"
         >
           <view class="status-title">处理状态</view>
           <image
             class="status-content"
             :src="getStatusImageSrc"
             mode="widthFix"
           ></image>
           <view class="status-content-text">
             <view>告警</view>
             <view>接警</view>
             <view>处理</view>
             <view>审核</view>
           </view>
          <image
            class="left-bottom"
            src="/static/img/left-bottom.png"
            mode="widthFix"
          ></image>
          <image
            class="right-bottom"
            src="/static/img/right-bottom.png"
            mode="widthFix"
          ></image>
          <image
            class="left-top"
            src="/static/img/left-top.png"
            mode="widthFix"
          ></image>
          <image
            class="right-top"
            src="/static/img/right-top.png"
            mode="widthFix"
          ></image>
        </view>
        <!-- 普通流程合并卡片 -->
        <view v-if="showNormalFlow" class="content-card">
          <view class="card-title">问题描述</view>
          <view class="card-content">{{ currentAlarm?.problemDescription }}</view>
          <view class="card-title">原因分析</view>
          <view class="card-content">{{ currentAlarm?.causeAnalysis }}</view>
          <view class="card-title">处理方法</view>
          <view class="card-content">{{ currentAlarm?.solutionMethod }}</view>
          <view v-if="currentAlarm?.alertProcessImages && currentAlarm.alertProcessImages.length > 0" class="card-title">图片查看</view>
          <scroll-view v-if="currentAlarm?.alertProcessImages && currentAlarm.alertProcessImages.length > 0" class="image-list" scroll-x>
            <image
              v-for="(img, idx) in currentAlarm?.alertProcessImages || []"
              :key="idx"
              :src="img.fileUrl"
              class="image-item"
              mode="aspectFill"
              @click="previewImage(img.fileUrl, (currentAlarm?.alertProcessImages || []).map(item => item.fileUrl))"
            />
          </scroll-view>
          <image
            class="left-bottom"
            src="/static/img/left-bottom.png"
            mode="widthFix"
          ></image>
          <image
            class="right-bottom"
            src="/static/img/right-bottom.png"
            mode="widthFix"
          ></image>
          <image
            class="left-top"
            src="/static/img/left-top.png"
            mode="widthFix"
          ></image>
          <image
            class="right-top"
            src="/static/img/right-top.png"
            mode="widthFix"
          ></image>
        </view>
        <!-- 底部按钮 -->
        <view
          v-if="!isOnsite && hasPendingReview && globalStore.userInfo.modules.includes('audit')"
          class="action-buttons"
        >
          <view
            class="action-button reject-button"
            @click="mygo(`/pages/consolePages/reject?id=${getConfirmId}`)"
            >退回处理</view
          >
          <view class="action-button confirm-button" @click="handleConfirm"
            >审核确认</view
          >
        </view>
      </template>
      <view v-else class="no-data">暂无数据</view>
    </view>
  </view>
</template>

<script setup>
import Navbar from '@/components/Navbar.vue';
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useGlobalStore } from '@/store/app';
import { mygo } from '@/utils/useNavigator';
import { createRequest } from '@/utils/request';

const globalStore = useGlobalStore();
const alarmId = ref('');
const isOnsite = ref(false);
const status = ref(0); // 状态参数：1-待确认，2-待处理，3-待审核，0-默认值
const alertTime = ref(''); // 告警时间
const receiveTime = ref(''); // 接警时间
const confirmId = ref(''); // 提交ID

// 告警数据
const alarmData = ref([]);
const loading = ref(false);

// 获取当前告警信息
const currentAlarm = computed(() => {
  if (alarmData.value.length === 0) return null;
  
  // 如果有 returnRound = 0 的记录，返回它（最新一次处理记录）
  const normalRecord = alarmData.value.find(record => record.returnRound === 0);
  if (normalRecord) {
    return normalRecord;
  }
  
  // 如果没有 returnRound = 0，返回数组最后一个元素
  return alarmData.value[alarmData.value.length - 1];
});

// 获取待审核记录的ID（用于确认审核）
const getConfirmId = computed(() => {
  const pendingRecord = alarmData.value.find(record => record.returnRound === 0);
  return pendingRecord?.id || '';
});

// 根据状态获取对应的状态图片
const getStatusImageSrc = computed(() => {
  // 根据status参数判断状态
  // status: 1 - 待确认, 2 - 待处理, 3 - 待审核
  switch (status.value) {
    case 1:
      // 待确认状态
      return '/static/img/consolePages/status-confirm.png'; // 待确认状态图片
    case 2:
      // 待处理状态
      return '/static/img/consolePages/status-process.png'; // 待处理状态图片
    case 3:
      // 待审核状态
      return '/static/img/consolePages/status-review.png'; // 待审核状态图片
    default:
      // 默认状态
      return '/static/img/consolePages/status-process.png'; // 默认状态图片
  }
});

// 获取退回记录（按 returnRound 从大到小排序）
const rejectRecords = computed(() => {
  return alarmData.value
    .filter(record => record.returnRound > 0)
    .sort((a, b) => b.returnRound - a.returnRound);
});

// 获取普通流程记录（returnRound = 0）
const normalRecords = computed(() => {
  return alarmData.value.filter(record => record.returnRound === 0);
});

// 判断是否有待审核状态
const hasPendingReview = computed(() => {
  return status.value === 3 && alarmData.value.some(record => record.returnRound === 0);
});

// 判断是否显示普通流程部分
const showNormalFlow = computed(() => {
  // 如果没有退回记录，直接显示普通流程
  if (rejectRecords.value.length === 0) {
    return true;
  }
  
  // 如果有退回记录且有 returnRound = 0，显示普通流程
  if (rejectRecords.value.length > 0 && hasPendingReview.value) {
    return true;
  }
  
  // 如果有退回记录但没有 returnRound = 0，不显示普通流程
  return false;
});

// 预览图片
const previewImage = (current, urls) => {
  // 过滤掉无效的图片URL
  const validUrls = urls.filter(
    url => url && typeof url === 'string' && url.trim() !== ''
  );

  // 确保current在validUrls中
  const currentIndex = validUrls.indexOf(current);
  if (currentIndex === -1) {
    current = validUrls[0];
  }

  uni.previewImage({
    current,
    urls: validUrls,
    fail: err => {
      console.error('图片预览失败:', err);
      uni.showToast({ title: '图片预览失败', icon: 'none' });
    },
  });
};

// 处理图片加载错误
const handleImageError = e => {
  console.error('图片加载失败:', e);
};

// 获取告警详情
const fetchAlarmDetail = async () => {
  if (!alarmId.value) return;
  
  loading.value = true;
  try {
    const response = await createRequest(`/alert/getAlertProcessInfo/${alarmId.value}`);
    
    if (response.code === 200 && response.data) {
      alarmData.value = response.data;
    }
  } catch (error) {
    console.error('获取告警详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 处理确认
const handleConfirm = async () => {
  try {
    const response = await createRequest('/alert/approve', {
      data: {
        alertProcessRecordId: getConfirmId.value
      }
    });

    uni.navigateBack();
  } catch (error) {
    uni.showToast({ title: '审核失败，请重试', icon: 'none' });
  }
};

onLoad(options => {
  alarmId.value = options.id;
  // 获取isOnsite参数，判断是否为现场角色
  isOnsite.value = options.isOnsite === 'true';
  // 获取status参数，判断告警状态
  status.value = parseInt(options.status) || 0;
  // 获取告警时间和接警时间
  alertTime.value = decodeURIComponent(options.alertTime || '');
  receiveTime.value = decodeURIComponent(options.receiveTime || '');

  if (!alarmId.value) {
    uni.showToast({ title: '告警ID缺失', icon: 'none' });
    setTimeout(() => {
      mygo('/pages/consolePages/consoleView');
    }, 500);
    return;
  }

  // 获取告警详情
  fetchAlarmDetail();
});
</script>

<style lang="scss" scoped>
.review-page {
  @include page-with-header;
  background: #172869;
  min-height: 100vh;
  padding-bottom: 130rpx;
}

.review-content {
  padding: 32rpx;
  padding-top: 0;
  box-sizing: border-box;
}

.content-card,
.reject-info-card,
.first-handle-card {
  padding: 32rpx;
  margin-top: 24rpx;
  border: 1rpx solid #50daff;
  background-color: #051749;
  position: relative;
}

.left-bottom {
  position: absolute;
  left: -1rpx;
  bottom: -1rpx;
  width: 16rpx;
  height: 16rpx;
}
.right-bottom {
  position: absolute;
  right: -1rpx;
  bottom: -1rpx;
  width: 16rpx;
  height: 16rpx;
}
.left-top {
  position: absolute;
  left: -1rpx;
  top: -1rpx;
  width: 16rpx;
  height: 16rpx;
}
.right-top {
  position: absolute;
  right: -1rpx;
  top: -1rpx;
  width: 16rpx;
  height: 16rpx;
}

.alarm-info-card {
  width: 686rpx;
  height: 314rpx;
  padding: 40rpx 30rpx;
  box-sizing: border-box;
  background-image: url('@/static/img/consolePages/alarm-info-card.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  margin-top: 48rpx;
}

.info-row {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 28rpx;
}

.info-label {
  color: rgba(255, 255, 255, 0.5);
  min-width: 160rpx;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  text-align: right;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 500;
}

.card-title {
  font-size: 30rpx;
  color: rgba(255, 255, 255, 0.8);
  font-weight: bold;
  margin-bottom: 24rpx;
}

.card-content {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.6;
  margin-bottom: 24rpx;
}

.image-list {
  display: flex;
  gap: 16rpx;
  overflow-x: auto;
  white-space: nowrap;
}

.image-item {
  width: 160rpx;
  height: 160rpx;
  object-fit: cover;
  background: #a2a2a2;
  flex-shrink: 0;
  margin-right: 16rpx;
  border: 1rpx solid #50daff;
}

.action-buttons {
  position: fixed;
  bottom: 40rpx;
  left: 24rpx;
  right: 24rpx;
  display: flex;
  justify-content: center;
  gap: 24rpx;
  z-index: 100;
}

.action-button {
  text-align: center;
  line-height: 88rpx;
  border-radius: 44rpx;
  font-size: 30rpx;
  transition: all 0.3s ease;
  height: 88rpx;
}

.reject-button {
  flex: 1;
  background: linear-gradient(135deg, #ff4757, #ff3838);
  color: #fff;
  box-shadow: 0 8rpx 24rpx rgba(255, 71, 87, 0.3);
}

.reject-button:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 12rpx rgba(255, 71, 87, 0.3);
}

.confirm-button {
  flex: 1.2;
  background: linear-gradient(135deg, #279bd5, #2264eb);
  color: #fff;
  box-shadow: 0 8rpx 24rpx rgba(30, 200, 225, 0.3);
}

.confirm-button:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 12rpx rgba(30, 200, 225, 0.3);
}

.reject-records {
  margin-bottom: 24rpx;
}

.reject-record-card {
  margin-bottom: 32rpx;
  padding-bottom: 24rpx;
}

.reject-record-card:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.history-tip {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.6);
  text-align: center;
  margin-top: 24rpx;
  padding: 16rpx 0 24rpx;
  font-weight: 500;
}

.divider {
  height: 1rpx;
  background-color: rgba(30, 200, 225, 0.1);
  margin-top: 24rpx;
  margin-bottom: 24rpx;
}

// 加载状态样式
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
}

.loading-text {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.6);
}

// 状态卡片样式
.status-title {
  font-size: 30rpx;
  color: rgba(255, 255, 255, 0.8);
  font-weight: bold;
  margin-bottom: 24rpx;
}

.status-content {
  width: 100%;
  height: 120rpx;
  margin-bottom: 16rpx;
}

.status-content-text {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.6);
  padding: 0 20rpx;
  box-sizing: border-box;
}
.no-data {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.6);
  text-align: center;
  margin-top: 24rpx;
}
</style>
